#include <iostream>
#include <cassert>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

// 父进程读数据，子进程写数据
int main()
{
    int pipefd[2] = {0};
    int piperet = pipe(pipefd);
    assert(piperet == 0);
    //(void*)piperet;

    pid_t id = fork();
    if (id < 0)
    {
        perror("create process fail");
        return 1;
    }
    if (id == 0)
    {
        close(pipefd[0]);
        // 子进程，将要做写数据的事情
        for (int i = 0; i < 10; i++)
        {
            char wbuffer[1024];

            snprintf(wbuffer, sizeof(wbuffer), "我是子进程，我的pid是：%d, 编号：%d", getpid(), i);

            write(pipefd[1], wbuffer, strlen(wbuffer));

            sleep(1);
        }

        // 子进程退出
        exit(0);
    }

    close(pipefd[1]);
    // 父进程将要做读数据的事
    while (true)
    {
        char rbuffer[1024];
        // 这里减一的原因是防止读取文件内容的时候超过数组大小，给斜杠零的预留位，因为文件本身是不涵盖斜杠零的
        ssize_t sz = read(pipefd[0], rbuffer, sizeof(rbuffer) - 1);

        if (sz > 0)
        {
            cout << "我是父进程，我的id是：" << getpid() << ", 我收到的消息是：" << rbuffer << endl;
        }
        else
            break;
    }

    // 回收子进程
    int status = 0;
    int wret = waitpid(id, &status, 0);
    if (wret == id)
    {
        cout << "wait process success：" << id << endl;
    }
    return 0;
}